from rest_framework.response import Response

from apps.minapp.models import Staff, Window
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin, RetrieveModelMixin, \
    UpdateModelMixin, DestroyModelMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import GenericViewSet
from rest_framework import serializers
from django_filters.rest_framework import DjangoFilterBackend, FilterSet, CharFilter
from rest_framework.filters import OrderingFilter, SearchFilter


class StaffSerializer(serializers.ModelSerializer):
    title = serializers.SerializerMethodField()
    gender = serializers.SerializerMethodField()

    class Meta:
        model = Staff
        exclude = ['openid', 'session_key', 'token', 'password', 'avatar']

    def get_title(self, obj):
        return obj.shop.title

    def get_gender(self, obj):
        return obj.get_gender_display()


class StaffPagination(PageNumberPagination):
    page_size = 5
    page_query_param = 'pageNum'
    page_size_query_param = 'pageSize'
    max_page_size = 20


class StaffView(ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin,
                DestroyModelMixin, GenericViewSet):
    authentication_classes = []

    queryset = Staff.objects.all().filter(disabled=False).order_by('id')
    serializer_class = StaffSerializer

    filter_backends = [SearchFilter]
    search_fields = ['workid', 'nickname', 'gender', 'shop__title']

    pagination_class = StaffPagination

    def create(self, request, *args, **kwargs):
        newStaff_data = request.data
        del newStaff_data['title']
        newStaff = Staff.objects.create(**newStaff_data)
        newStaff.save()
        return Response({"error_num": 0})

    def update(self, request, *args, **kwargs):
        staff_id = kwargs['pk']
        staff_data = request.data
        del staff_data['title']
        try:
            staff = Staff.objects.get(id=staff_id)
            staff.__dict__.update(**staff_data)
            staff.save()
        except Exception as e:
            print(e)
        return Response({'error_num': 0})

    def delete(self, request, *args, **kwargs):
        staff_id = kwargs['pk']
        try:
            staff = Staff.objects.get(id=staff_id)
            staff.disabled = True
            staff.save()
        except Exception as e:
            print(e)
        return Response({'error_num': 0})
